package org.dfzt.modules.system.controller;

import java.io.IOException;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dfzt.common.api.vo.Result;
import org.dfzt.common.constant.CacheConstant;
import org.dfzt.common.constant.CommonConstant;
import org.dfzt.common.system.service.ISysBaseAPI;
import org.dfzt.common.system.query.QueryGenerator;
import org.dfzt.common.system.util.JwtUtil;
import org.dfzt.common.system.vo.LoginUser;
import org.dfzt.common.util.ImportExcelUtil;
import org.dfzt.common.util.VerifyParam;
import org.dfzt.common.util.oConvertUtils;
import org.dfzt.modules.system.entity.SysDepart;
import org.dfzt.modules.system.model.DepartIdModel;
import org.dfzt.modules.system.model.SysDepartTreeModel;
import org.dfzt.modules.system.service.ISysDepartService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;



/**
 * <p>
 * 部门表 前端控制器
 * <p>
 *
 * @Author: Steve @Since： 2019-01-22
 */
@RestController
@RequestMapping("/sys/sysDepart")

public class SysDepartController {
	private static final Log log = LogFactory.getLog(SysDepartController.class);

	@Autowired
	private ISysDepartService sysDepartService;
	@Autowired
	public RedisTemplate<String, Object> redisTemplate;
	@Resource
	private ISysBaseAPI sysBaseAPI;
	/**
	 * 查询数据 查出我的部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryMyDeptTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryMyDeptTreeList() {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		try {
			if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
				List<SysDepartTreeModel> list = sysDepartService.queryMyDeptTreeList(user.getDepartIds());
				result.setResult(list);
				result.setMessage(CommonConstant.USER_IDENTITY_2.toString());
				result.setSuccess(true);
			}else{
				result.setMessage(CommonConstant.USER_IDENTITY_1.toString());
				result.setSuccess(true);
			}
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 查询数据 查出所有部门,并以树结构数据格式响应给前端
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryTreeList", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> queryTreeList(String parentId) {
		Result<List<SysDepartTreeModel>> result = new Result<>();
		if(parentId!=null){
			if(!VerifyParam.verifyParam("parentId",parentId,"SysDepart")){
				result.error500("数据范围验证失败！");
				return result;
			}
		}
		try {
			List<SysDepartTreeModel> list = sysDepartService.queryTreeList(parentId);
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 添加新数据 添加用户新建的部门对象数据,并保存到数据库
	 *
	 * @param sysDepart
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
    @RequiresPermissions("url:/sys/sysDepart/add")
	public Result<SysDepart> add(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		Result<SysDepart> result = new Result<SysDepart>();
		if(!VerifyParam.verifyParam("SysDepart",sysDepart,"object")){
			result.error500("数据范围验证失败！");
			return result;
		}
		String username = JwtUtil.getUserNameByToken(request);
		try {
			sysDepart.setCreateBy(username);
			sysDepartService.saveDepartData(sysDepart, username);
			//清除部门树内存
			// FindsDepartsChildrenUtil.clearSysDepartTreeList();
			// FindsDepartsChildrenUtil.clearDepartIdModel();
			result.success("添加成功！");
			sysBaseAPI.addLog("部门["+ sysDepart.getDepartName()+"]添加成功",
					CommonConstant.TYPE_SYSTEM,CommonConstant.OPERATE_TYPE_ADD, CommonConstant.FLAG_SUCCESS,null);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			result.error500("操作失败");
			sysBaseAPI.addLog("部门["+ sysDepart.getDepartName()+"]添加失败",
					CommonConstant.TYPE_SYSTEM,CommonConstant.OPERATE_TYPE_ADD, CommonConstant.FLAG_FAIL,null);
		}
		return result;
	}

	/**
	 * 编辑数据 编辑部门的部分数据,并保存到数据库
	 *
	 * @param sysDepart
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
    @RequiresPermissions("url:/sys/sysDepart/edit")
    public Result<SysDepart> edit(@RequestBody SysDepart sysDepart, HttpServletRequest request) {
		Result<SysDepart> result = new Result<SysDepart>();
		if(!VerifyParam.verifyParam("SysDepart",sysDepart,"object")){
			result.error500("数据范围验证失败！");
			return result;
		}
		String username = JwtUtil.getUserNameByToken(request);
		sysDepart.setUpdateBy(username);
		SysDepart sysDepartEntity = sysDepartService.getById(sysDepart.getId());
		if (sysDepartEntity == null) {
			result.error500("未找到对应实体");
			sysBaseAPI.addLog("部门["+ sysDepart.getDepartName()+"]更新失败",
					CommonConstant.TYPE_SYSTEM,CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_FAIL,null);

		} else {
			boolean ok = sysDepartService.updateDepartDataById(sysDepart, username);
			// TODO 返回false说明什么？
			if (ok) {
				//清除部门树内存
				//FindsDepartsChildrenUtil.clearSysDepartTreeList();
				//FindsDepartsChildrenUtil.clearDepartIdModel();
				result.success("修改成功!");
				sysBaseAPI.addLog("部门["+ sysDepart.getDepartName()+"]更新成功",
						CommonConstant.TYPE_SYSTEM,CommonConstant.OPERATE_TYPE_UPDATE, CommonConstant.FLAG_SUCCESS,null);

			}
		}
		return result;
	}

	/**
	 *   通过id删除
	 * @param id
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
    @RequiresPermissions("url:/sys/sysDepart/delete")
    public Result<SysDepart> delete(@RequestParam(name="id",required=true) String id) {

		Result<SysDepart> result = new Result<SysDepart>();
		if(!VerifyParam.verifyParam("id",id,"SysDepart")){
			result.error500("数据范围验证失败！");
			return result;
		}
		SysDepart sysDepart = sysDepartService.getById(id);
		if(sysDepart==null) {
			result.error500("未找到对应实体");
			sysBaseAPI.addLog("部门删除失败",
					CommonConstant.TYPE_SYSTEM,CommonConstant.OPERATE_TYPE_DELETE, CommonConstant.FLAG_FAIL,null);

		}else {
			boolean ok = sysDepartService.delete(id);
			if(ok) {
				//清除部门树内存
				//FindsDepartsChildrenUtil.clearSysDepartTreeList();
				// FindsDepartsChildrenUtil.clearDepartIdModel();
				result.success("删除成功!");
				sysBaseAPI.addLog("部门["+ sysDepart.getDepartName()+"]删除成功",
						CommonConstant.TYPE_SYSTEM,CommonConstant.OPERATE_TYPE_DELETE, CommonConstant.FLAG_SUCCESS,null);

			}
		}
		return result;
	}


	/**
	 * 批量删除 根据前端请求的多个ID,对数据库执行删除相关部门数据的操作
	 *
	 * @param ids
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	@RequiresPermissions("url:/sys/sysDepart/deleteBatch")
    public Result<SysDepart> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

		Result<SysDepart> result = new Result<SysDepart>();
		if(!VerifyParam.verifyParam("ids",ids)){
			result.error500("数据范围验证失败！");
			return result;
		}
		if (ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			this.sysDepartService.deleteBatchWithChildren(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * 查询数据 添加或编辑页面对该方法发起请求,以树结构形式加载所有部门的名称,方便用户的操作
	 *
	 * @return
	 */
	@RequestMapping(value = "/queryIdTree", method = RequestMethod.GET)
	public Result<List<DepartIdModel>> queryIdTree(String parentId) {
		Result<List<DepartIdModel>> result = new Result<>();
		if(!VerifyParam.verifyParam("parentId",parentId,"SysDepart")){
			result.error500("数据范围验证失败！");
			return result;
		}
		try {
			List<DepartIdModel> list = sysDepartService.queryDepartIdTreeList(parentId);
			result.setResult(list);
			result.setSuccess(true);
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 部门搜索功能方法,根据关键字模糊搜索相关部门
	 * @param keyWord
	 * @return
	 */
	@RequestMapping(value = "/searchBy", method = RequestMethod.GET)
	public Result<List<SysDepartTreeModel>> searchBy(@RequestParam(name = "keyWord", required = true) String keyWord,
													 @RequestParam(name = "myDeptSearch", required = false) String myDeptSearch) {
		Result<List<SysDepartTreeModel>> result = new Result<List<SysDepartTreeModel>>();
		if(!VerifyParam.verifyParam("departName",keyWord,"SysDepart")){
			result.error500("数据范围验证失败！");
			return result;
		}
		//部门查询，myDeptSearch为1时为我的部门查询，登录用户为上级时查只查负责部门下数据
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String departIds = null;
		if(oConvertUtils.isNotEmpty(user.getUserIdentity()) && user.getUserIdentity().equals( CommonConstant.USER_IDENTITY_2 )){
			departIds = user.getDepartIds();
		}
		List<SysDepartTreeModel> treeList = this.sysDepartService.searhBy(keyWord,myDeptSearch,departIds);
		if (treeList == null || treeList.size() == 0) {
			result.setSuccess(false);
			result.setMessage("未查询匹配数据！");
			return result;
		}
		result.setResult(treeList);
		return result;
	}


	/**
	 * 导出excel
	 *
	 * @param request
	 */
	@RequestMapping(value = "/exportXls")
    @RequiresPermissions("url:/sys/sysDepart/exportXls")
	public ModelAndView exportXls(SysDepart sysDepart,HttpServletRequest request) {
		// Step.1 组装查询条件
		QueryWrapper<SysDepart> queryWrapper = QueryGenerator.initQueryWrapper(sysDepart, request.getParameterMap());
		//Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<SysDepart> pageList = sysDepartService.list(queryWrapper);
		//按字典排序
		Collections.sort(pageList, new Comparator<SysDepart>() {
			@Override
			public int compare(SysDepart arg0, SysDepart arg1) {
				return arg0.getId().compareTo(arg1.getId());
			}
		});
		//导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "部门列表");
		mv.addObject(NormalExcelConstants.CLASS, SysDepart.class);
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("部门列表数据", "导出人:"+user.getRealname(), "导出信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	//@RequiresRoles({"admin"})
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	@CacheEvict(value= {CacheConstant.SYS_DEPARTS_CACHE,CacheConstant.SYS_DEPART_IDS_CACHE}, allEntries=true)
	@RequiresPermissions("url:/sys/sysDepart/importExcel")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<String> errorMessageList = new ArrayList<>();
		List<SysDepart> listSysDeparts = null;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			String filename = file.getOriginalFilename();
			if(filename==null||!filename.endsWith(".xls")||!filename.endsWith("xlsx")){
				return Result.error("文件格式有误！");
			}
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				// orgCode编码长度
				int codeLength = 3;
				listSysDeparts = ExcelImportUtil.importExcel(file.getInputStream(), SysDepart.class, params);
				//按长度排序
				Collections.sort(listSysDeparts, new Comparator<SysDepart>() {
					@Override
					public int compare(SysDepart arg0, SysDepart arg1) {
						return arg0.getId().length() - arg1.getId().length();
					}
				});

				int num = 0;
				for (SysDepart sysDepart : listSysDeparts) {
					String orgCode = sysDepart.getId();
					if(orgCode.length() > codeLength) {
						String parentCode = orgCode.substring(0, orgCode.length()-codeLength);
						QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<SysDepart>();
						queryWrapper.eq("org_code", parentCode);
						try {
							SysDepart parentDept = sysDepartService.getOne(queryWrapper);
							if(!parentDept.equals(null)) {
								sysDepart.setParentId(parentDept.getId());
							} else {
								sysDepart.setParentId("");
							}
						}catch (Exception e) {
							//没有查找到parentDept
						}
					}else{
						sysDepart.setParentId("");
					}
					sysDepart.setDelFlag(CommonConstant.DEL_FLAG_0.toString());
					ImportExcelUtil.importDateSaveOne(sysDepart, ISysDepartService.class, errorMessageList, num, CommonConstant.SQL_INDEX_UNIQ_DEPART_ORG_CODE);
					num++;
				}
				//清空部门缓存
				Set keys3 = redisTemplate.keys(CacheConstant.SYS_DEPARTS_CACHE + "*");
				Set keys4 = redisTemplate.keys(CacheConstant.SYS_DEPART_IDS_CACHE + "*");
				redisTemplate.delete(keys3);
				redisTemplate.delete(keys4);
				return ImportExcelUtil.imporReturnRes(errorMessageList.size(), listSysDeparts.size() - errorMessageList.size(), errorMessageList);
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}


	/**
	 * 查询所有部门信息
	 * @return
	 */
	@GetMapping("listAll")
	public Result<List<SysDepart>> listAll(@RequestParam(name = "id", required = false) String id) {
		Result<List<SysDepart>> result = new Result<>();
		LambdaQueryWrapper<SysDepart> query = new LambdaQueryWrapper<SysDepart>();
		query.orderByAsc(SysDepart::getId);
		if(oConvertUtils.isNotEmpty(id)){
			String[] arr = id.split(",");
			query.in(SysDepart::getId,arr);
		}
		List<SysDepart> ls = this.sysDepartService.list(query);
		result.setSuccess(true);
		result.setResult(ls);
		return result;
	}
}
